package net.jiastudy.biz.targettask.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import net.jiastudy.biz.enums.AuditStatus;
import net.jiastudy.biz.targettask.entity.ImportWorkReponseVo;
import net.jiastudy.biz.targettask.entity.ImportWorkVo;
import net.jiastudy.biz.targettask.entity.TargetTask;
import net.jiastudy.biz.targettask.entity.TargetWork;
import net.jiastudy.biz.targettask.entity.TaskYear;
import net.jiastudy.biz.targettask.mapper.TargetWorkMapper;
import net.jiastudy.biz.targettask.service.TargetTaskService;
import net.jiastudy.biz.targettask.service.TargetWorkService;
import net.jiastudy.biz.user.entity.User;
import net.jiastudy.biz.user.service.UserService;
import net.jiastudy.core.base.BaseService;
import net.jiastudy.core.exception.ServiceException;
import net.jiastudy.core.utils.BeanUtils;
import org.apache.poi.hpsf.Date;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional(rollbackFor = Exception.class)
public class TargetWorkServiceImpl extends BaseService<TargetWorkMapper, TargetWork> implements TargetWorkService {
    @Resource
    private TargetTaskService targetTaskService;

    @Resource
    UserService userService;

    @Override
    public TargetWork createWork(TargetWork targetWork) {
        TargetTask targetTask = targetTaskService.getTargetTask(targetWork.getTargetTaskId());

        if (null == targetTask) {
            throw new ServiceException("该目标任务不存在");
        }

        if (targetTask.getStatus() == AuditStatus.approving) {
            throw new ServiceException("该任务未通过审核，不能布置作业！");
        }

        targetWork.setDeptId(targetTask.getReceiveDeptId());

        User user = getCurrentUser();
        targetWork.setCreatedUserId(user.getId());

        if (this.insert(targetWork)) {
            return targetWork;
        }

        return null;
    }

    @Override
    public Boolean deleteWorksByTaskId(Long taskId) {
        Wrapper<TargetWork> wrapper = new EntityWrapper<>();
        wrapper.eq("target_task_id", taskId);

        return this.delete(wrapper);
    }

    @Override
    public Boolean deleteWorkById(Long id) {
        return this.deleteById(id);
    }

    @Override
    public List<ImportWorkVo> findMyDeptCurrentYearWorks() {
        User currentUser = getCurrentUser();
        if (null == currentUser.getDeptId()) {
            throw new ServiceException("您不属于任何部门，请先加入部门！");
        }

        Calendar now = Calendar.getInstance();
        String code = String.valueOf(now.get(Calendar.YEAR));
        TaskYear year = targetTaskService.getTaskYearByCode(code);
        if (null == year) {
            throw new ServiceException(code + "目标年度不存在，不能导入");
        }

        List<TargetTask> tasks = targetTaskService.findTargetTasksByDeptIdAndYear(currentUser.getDeptId(), year.getId());
        Map<Long, String> sourceMap = new HashMap<Long, String>();
        for (TargetTask targetTask : tasks) {
            sourceMap.put(targetTask.getId(), targetTask.getOrigin());
        }
        Set<Long> taskIds = BeanUtils.getFiled(tasks, "id", long.class);

        Wrapper<TargetWork> wrapper = new EntityWrapper<>();
        wrapper.in("target_task_id", taskIds);
        List<TargetWork> works = this.selectList(wrapper);
        List<ImportWorkVo> result = new ArrayList<>();

        for (TargetWork targetWork : works) {
            Set<Long> allUserIds = new HashSet<>();
            ImportWorkVo importWorkVo = new ImportWorkVo();
            importWorkVo.setName(targetWork.getTitle());
            String[] startDateStr = targetWork.getStartDate().split("-");
            Integer startDate = Integer.valueOf(startDateStr[1]);
            importWorkVo.setStartDate(startDate);

            String[] endDateStr = targetWork.getEndDate().split("-");
            Integer endDate = Integer.valueOf(endDateStr[1]);
            importWorkVo.setEndDate(endDate);
            importWorkVo.setSeq(targetWork.getSeq());
            String userIds;

            allUserIds.add(targetWork.getResponsibleUserId());
            userIds = targetWork.getResponsibleUserId().toString();
            if (null != targetWork.getAssistUserId()) {
                userIds = userIds + "," + targetWork.getAssistUserId().toString();
                allUserIds.add(targetWork.getAssistUserId());
            }
            importWorkVo.setUserIds(userIds);
            List<User> users = userService.findUsersByIds(allUserIds);
            importWorkVo.setUsers(users);
            importWorkVo.setSource(sourceMap.get(targetWork.getTargetTaskId()));
            result.add(importWorkVo);
        }

        return result;
    }

    @Override
    public List<TargetWork> findByTaskId(Long taskId) {
        Wrapper<TargetWork> wrapper = new EntityWrapper<>();
        wrapper.eq("target_task_id", taskId);

        return this.selectList(wrapper);
    }

    @Override
    public TargetWork updateTargetWork(TargetWork targetWork) {
        if (this.updateById(targetWork)) {
            return targetWork;
        }

        return null;
    }
}
